<?php
/**
* This file holds a class for Application_Model_UserMapper.
* @package busmap
*/

/**
* This class holds Application_Model_UserMapper class, that maps User objects to the database entries.
* @package busmap
*/
class Application_Model_UserMapper
{
	protected $_dbTable;
 
	/**
	* Function that sets the database table for the User objects.
	*/
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
    /**
	* Function that gets the database table for the User objects.
	*/
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_User');
		}
		return $this->_dbTable;
	}
 
	/**
	* Function that saves the given User object to the database.
	* If id is set, existing entry will be updated.
	* Otherwise a new entry will be inserted with the add_time set to current timestamp.
	*/
	public function save(Application_Model_User $user)
	{
		$data = array(
			'username'   => $user->getUsername(),
			'fullname' => $user->getFullname(),
			'password' => $user->getPassword(),
			'email' => $user->getEmail(),
			'level' => $user->getLevel(),
		);
 
		if (null === ($id = $user->getId())) {
			unset($data['id']);
			$data['add_time'] = time();
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}

	/**
	* Function that finds a User entry with the given id.
	* Given reference object will be used to hold the data.
	*/
	public function find($id, Application_Model_User $user)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$user->setId($row->id)
				  ->setUsername($row->username)
				  ->setFullname($row->fullname)
				  ->setEmail($row->email)
				  ->setPassword($row->password)
				  ->setLevel($row->level)
				  ->setAddTime($row->add_time)
				  ->setDeletedTime($row->deleted_time);
	}

	/**
	* Function that finds all User entries from the database.
	* Returns an array with User objects corresponding to the found entries.
	*/
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_User();
			$entry->setId($row->id)
				  ->setUsername($row->username)
				  ->setFullname($row->fullname)
				  ->setEmail($row->email)
				  ->setPassword($row->password)
				  ->setLevel($row->level)
				  ->setAddTime($row->add_time)
				  ->setDeleteTime($row->delete_time);

			$entries[] = $entry;
		}
		return $entries;


	}

}
